program_name='crc16-xmodem'

define_variable

volatile integer g_pCRC16XModemTable[256] = {
    $0000, $17ce, $0fdf, $1811, $1fbe, $0870, $1061, $07af,
    $1f3f, $08f1, $10e0, $072e, $0081, $174f, $0f5e, $1890,
    $1e3d, $09f3, $11e2, $062c, $0183, $164d, $0e5c, $1992,
    $0102, $16cc, $0edd, $1913, $1ebc, $0972, $1163, $06ad,
    $1c39, $0bf7, $13e6, $0428, $0387, $1449, $0c58, $1b96,
    $0306, $14c8, $0cd9, $1b17, $1cb8, $0b76, $1367, $04a9,
    $0204, $15ca, $0ddb, $1a15, $1dba, $0a74, $1265, $05ab,
    $1d3b, $0af5, $12e4, $052a, $0285, $154b, $0d5a, $1a94,
    $1831, $0fff, $17ee, $0020, $078f, $1041, $0850, $1f9e,
    $070e, $10c0, $08d1, $1f1f, $18b0, $0f7e, $176f, $00a1,
    $060c, $11c2, $09d3, $1e1d, $19b2, $0e7c, $166d, $01a3,
    $1933, $0efd, $16ec, $0122, $068d, $1143, $0952, $1e9c,
    $0408, $13c6, $0bd7, $1c19, $1bb6, $0c78, $1469, $03a7,
    $1b37, $0cf9, $14e8, $0326, $0489, $1347, $0b56, $1c98,
    $1a35, $0dfb, $15ea, $0224, $058b, $1245, $0a54, $1d9a,
    $050a, $12c4, $0ad5, $1d1b, $1ab4, $0d7a, $156b, $02a5,
    $1021, $07ef, $1ffe, $0830, $0f9f, $1851, $0040, $178e,
    $0f1e, $18d0, $00c1, $170f, $10a0, $076e, $1f7f, $08b1,
    $0e1c, $19d2, $01c3, $160d, $11a2, $066c, $1e7d, $09b3,
    $1123, $06ed, $1efc, $0932, $0e9d, $1953, $0142, $168c,
    $0c18, $1bd6, $03c7, $1409, $13a6, $0468, $1c79, $0bb7,
    $1327, $04e9, $1cf8, $0b36, $0c99, $1b57, $0346, $1488,
    $1225, $05eb, $1dfa, $0a34, $0d9b, $1a55, $0244, $158a,
    $0d1a, $1ad4, $02c5, $150b, $12a4, $056a, $1d7b, $0ab5,
    $0810, $1fde, $07cf, $1001, $17ae, $0060, $1871, $0fbf,
    $172f, $00e1, $18f0, $0f3e, $0891, $1f5f, $074e, $1080,
    $162d, $01e3, $19f2, $0e3c, $0993, $1e5d, $064c, $1182,
    $0912, $1edc, $06cd, $1103, $16ac, $0162, $1973, $0ebd,
    $1429, $03e7, $1bf6, $0c38, $0b97, $1c59, $0448, $1386,
    $0b16, $1cd8, $04c9, $1307, $14a8, $0366, $1b77, $0cb9,
    $0a14, $1dda, $05cb, $1205, $15aa, $0264, $1a75, $0dbb,
    $152b, $02e5, $1af4, $0d3a, $0a95, $1d5b, $054a, $1284
}

(******************************************
*  XMODEM CRC16 with $0000 as polynomial
*  
*  Usage:  crc16c('stringToCRC')
*
*******************************************)
define_function integer crc16x (char crcString16x[255]) {
    stack_var integer m_crc16x
    stack_var integer i
    m_crc16x = $0000
    for(i = 1; i < length_string(crcString16x)+1; i++) {
	m_crc16x = g_pCRC16XModemTable[((m_crc16x ^ crcString16x[i]) & $FF)+1] ^ (m_crc16x >> 8);
    }
    return m_crc16x
}

